#!/usr/bin/perl -w

BEGIN {
        if(!exists($::ENV{TRUECL_CODE})) {
                die("Missing TRUECL_CODE environment variable.");
        }
        if(!exists($::ENV{TRUECL_LOG})) {
                die("Missing TRUECL_LOG environment variable.");
        }
        if(!exists($::ENV{TRUECL_CFG})) {
                die("Missing TRUECL_CFG environment variable.");
        }
	push @::INC,"$::ENV{TRUECL_CODE}/lib";
}

use nethardware;
use ipinterfaces;
use clnet qw(CLNET2_checklink CLNET2_physical_link_checking);
use Time::HiRes qw(time);
use Getopt::Long;

$once=0;

GetOptions("once" => \$once);
$card=$ARGV[0];
if(!defined($card)) {
	print STDERR "Usage: check_netlink_function netcard\n";
	exit(1);
}

$network_info=new nethardware();
@available_cards=$network_info->list();
if(! grep {$_ eq $card} @available_cards) {
	print STDERR "Error: Network card '$card' is not available.\n";
	exit(1);
}

($supported,$freq)=CLNET2_physical_link_checking();
if(! $supported) {
	print STDERR "Error: Physical link checking is not currently supported.\n";
	exit(1);
}
print "Physical link checking is supported overall - at ${freq}Hz.\n";

if($network_info->is_aggr($card)) {
	print "Network physical link level checking not appropriate:\n'$card' has external network aggregation.\n";
	exit(2);
}

$ipinters=new ipinterfaces();
# For hp-ux we currently cludge link level checking using linkloop, 
# so we need to get more details from the card in question...
$is_hp=1 if $^O eq "hpux";
$dd=$ipinters->get_details(interface=>$card);
if(defined($dd)) {
	$c_hw=$dd->{mac};
	$c_hw =~ s/://g;
	$c_ci=$dd->{ci};
} else {
	print STDERR "Error: Unable to get hardware details for card '$card'.\n";
	exit(1);
}

if($is_hp) {
	($r,$r2)=CLNET2_checklink(card => $card, hw => $c_hw, ci => $c_ci);
} else {
	($r,$r2)=CLNET2_checklink(card => $card);
}

if($r==0) {
	print STDERR "Error: Physical link problem for network card '$card'.\n";
	exit(1);
}

exit(0) if $once;
print "Physical network link is fine ... timing multiple checks ...\n";

$stime=time();
$max=$freq*10;
$c=0;
while($c<$max) {
	if($is_hp) {
		($r,$r2)=CLNET2_checklink(card => $card, hw => $c_hw, ci => $c_ci);
	} else {
		($r,$r2)=CLNET2_checklink(card => $card);
	}
	$c++;
}
$etime=time();

$d=$etime-$stime;
$mf=int($max/$d);
print "$max link checks performed in $d seconds.\n";
print "Maximum frequency supported in theory is ~$mf\n";
exit(0);
